package com.mjf.utils;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池工具类
 */
public class ThreadPoolUtil {

    private static ThreadPoolExecutor threadPoolExecutor = null;

    private ThreadPoolUtil() {
    }

    public static ThreadPoolExecutor getThreadPool() {
        if (threadPoolExecutor == null) {
            synchronized (ThreadPoolUtil.class) {
                if (threadPoolExecutor == null) {
                    threadPoolExecutor = new ThreadPoolExecutor(
                            8,  // 核心线程数，及时没人用也不会被销毁
                            16, // 允许创建的最大线程数
                            1L, // 多余的空闲线程在销毁前等待的时间
                            TimeUnit.MINUTES,
                            new LinkedBlockingQueue<>() // 存放没有被执行的任务。等队列满了才会去创建新的线程，直到允许的最大线程数
                    );
                }
            }
        }
        return threadPoolExecutor;
    }

    public static void main(String[] args) {

        ThreadPoolExecutor threadPool = ThreadPoolUtil.getThreadPool();
        threadPool.setCorePoolSize(2);

        // new LinkedBlockingQueue<>(3) 给定一个比较小的队列进行测试什么时候创建新的线程
        for (int i = 0; i < 100; i++) {
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }


    }

}
